<template>
  <div class="box">
    <div class="head-fixed">
      <div class="head">
        <div class="head-div">
          <img src="../../assets/zjt2.png" alt="" class="back" @click="back()" />
        </div>
        <div class="head-search">公司资料</div>
        <div @click="save()">保存</div>
      </div>
    </div>
    <div class="content">
        <div class="inpBox">
        <span>LOGO</span>
        <input
          v-show="false"
          type="file"
          accept="image/*"
          @change="tirggerFile($event)"
          ref="input"
        />
        <div>
          <img
            src="../../assets/avatar.png"
            v-if="imgUrl == ''"
            alt=""
            @click="openImg"
          />
<!--v-if 表示元素是否移除或者插入, alt表示alt属性是img标签的必须属性，如果没有特别意义的图片，可以写alt=""-->
<!--@click是 绑定监听（单击事件）-->
          <img :src="imgUrl" alt="" v-if="imgUrl != ''" @click="openImg" />
        </div>
      </div>
      <div class="inpBox">
        <span>企业名称</span>
        <div>
          <input type="text" v-model="company_data.companyName" placeholder="请输入企业名称" />
        </div>
      </div>
      <div class="inpBox">
        <span>联系电话</span>
        <div>
          <input type="text" v-model="company_data.companyMobile" placeholder="请输入联系电话" />
        </div>
      </div>
      <div class="inpBox">
        <span>所在城市</span>
        <div @click="prop(1)">
          <input type="text" v-model="cityValue" placeholder="请选择工作城市" readonly/>
        </div>
<!-- 只读readonly，因为是下拉，不是填入-->
      </div>
      <div class="inpBox">
        <span>企业年限</span>
        <div @click="prop(5)">
          <input type="text" v-model="ageValue" placeholder="请选择企业年限" readonly/>
        </div>
      </div>
      <div class="inpBox">
        <span>企业规模</span>
        <div @click="prop(3)">
          <input type="text" v-model="stateValue" placeholder="请选择企业规模" readonly/>
        </div>
      </div>
      <div class="inpBox">
        <span>企业类型</span>
        <div>
          <input type="text" v-model="company_data.industry" placeholder="请输入企业类型" />
        </div>
      </div>
      <div class="inpBoxs">
        <div class="inpBox">
          <span>公司简介</span>
          <span>选填</span>
        </div>
        <textarea placeholder="请填写公司简介" v-model="company_data.companyIntroduction"></textarea>
      </div>
    </div>

    <mt-popup v-model="cityIf" position="bottom">
<!--bottom值越大，定位元素越往上移动-->
      <p class="mt-p">
        <span @click="off(1)">取消</span> 请选择城市
        <span @click="on(1)">确定</span>
      </p>
      <mt-picker :slots="city" valueKey="name" :visibleItemCount="5" @change="addressChange" class="picker"></mt-picker>
<!--  picker从底部弹起的滚动选择器，现支持五种选择器，通过mode来区分，分别是普通选择器，多列选择器，时间选择器，日期选择器，省市区选择器，默认是普通选择器-->
    </mt-popup>
    <mt-popup v-model="stateIf" position="bottom">
      <p class="mt-p">
        <span @click="off(3)">取消</span> 请选择企业规模
        <span @click="on(3)">确定</span>
      </p>
      <mt-picker
        :slots="stateLimit"
        @change="stateChange"
        value-key="name"
        class="picker"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="ageIf" position="bottom">
      <p class="mt-p">
        <span @click="off(5)">取消</span> 请选择年限
        <span @click="on(5)">确定</span>
      </p>
      <mt-picker
        :slots="ageLimit"
        @change="ageChange"
        value-key="name"
        class="picker"
      ></mt-picker>
    </mt-popup>
  </div>
</template>

<script>
import {Popup, Picker, Toast} from 'mint-ui'
// 引入省市区数据json文件
import threeLevelAddress from '../../assets/address.json'
import Vue from 'vue'
import da from 'element-ui/src/locale/lang/da'
var cityValue = ''
var cityCode = ''
var stateValue = ''
var ageValue = ''
var ageCode = ''
var stateCode = ''
export default { //export default 默认导出的成员
  inject: ['reload'],// inject是引入，但是这里没用到
  name: 'means',
  components: {Popup, Picker},//components页面主页，
  created () {//created 在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图
//写在method里也行，在这里写方法，在method里调用
    this.$http({
      method: 'get',
      url: Vue.prototype.AppURL + '/comuser/get/company/data'
    }).then(({data}) => {//.then是接收后台传过来的数据，data是自定义
      console.log(data)
      this.stateLimit = data.scale
      this.ageLimit = data.workYear
    })

    this.company_data.userId = localStorage.getItem('userId');//公司绑定的是注册登录的用户，如果填写了公司信息，之后就不用填写了
    // mounted在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
    // 获取公司编号
    this.companyId = localStorage.getItem('cache_company_id')
    if (this.notEmpty(this.companyId)) {
      this.updateBel = 1
      // 查询公司信息
      this.$http({
        method: 'get',
        url: Vue.prototype.AppURL + '/comuser/get/company/detail',
        params:{
          id: this.companyId
        }
      }).then(({data}) => {
        if (data) {
          this.company_data = data
          this.logo = data.logo
          this.imgUrl = Vue.prototype.AppURL + '/file/' + data.logo

          let citySplice = this.company_data.cityId + ""
          // 回显地区
          let cityData = this.getCountyData(citySplice.substring(0,2) + '0000',
            citySplice.substring(0, 4) + '00', citySplice)
          if (cityData) {
            this.cityValue = cityData.name
          }

          if (this.updateBel === 1 && this.stateLimit[0].values) {
            let list = this.stateLimit[0].values
            list.forEach((item) => {
              if (item.id === (this.company_data.scale - 0)) {
                this.stateValue = item.name
              }
            })
          }

          if (this.updateBel === 1 && this.ageLimit[0].values) {
            let list = this.ageLimit[0].values
            list.forEach((item) => {
              if (item.id === (this.company_data.companyYears - 0)) {
                this.ageValue = item.name
              }
            })
          }
        }
      })
    }
  },
  mounted () {

  },
  // data() 为变量赋值等
  data () {
    return {
      logo:"",
      updateBel: 0,
      companyId: null,
      company_data: {
        companyName: '',
        companyMobile: '',
        cityId: '',
        companyYears: '',
        scale: '',
        industry: '',
        companyIntroduction: '',
        logo: '',
        userId: ''
      },
      // status为状态，0是新增，1是修改
      status: localStorage.status,
      post: '',
      state: '',
      text: '',
      imgUrl: '',
      cityValue: '',
      cityIf: false,
      city: [
        // 省
        {
          flex: 1,
          values: this.getProvinceArr(), // 省份数组
          className: 'slot1',
          textAlign: 'center'
        },
        // 分隔符
        {
          divider: true,
          content: '',
          className: 'slot2'
        },
        // 市
        {
          flex: 1,
          values: this.getCityArr('北京市'),
          className: 'slot3',
          textAlign: 'center'
        },
        {
          divider: true,
          content: '',
          className: 'slot4'
        },
        // 县
        {
          flex: 1,
          values: this.getCountyArr('北京市', '北京市'),
          className: 'slot5',
          textAlign: 'center'
        }
      ],
      regionInit: false,
      stateValue: '',
      stateIf: false,
      stateLimit: [
        {
          values: []
        }
      ],
      ageValue: '',
      ageIf: false,
      ageLimit: [
        {
          values: []
        }
      ]
    }
  },
  // methods 编写js函数
  methods: {//方法都写这里
    notEmpty (val) {
      const re = new RegExp('^[ ]+$') //正则，去除空字符。匹配是否为空
      return !(val == null || val === '' || typeof (val) === 'undefined' || re.test(val))
    },
    save () {
      if (!this.notEmpty(this.company_data.logo)) {//相当于直接都调用了notEmpty ,不用重复写代码
        return Toast('请上传企业logo')
      }
      if (!this.notEmpty(this.company_data.companyName)) {
        return Toast('请输入企业名称')
      }
      if (!this.notEmpty(this.company_data.companyMobile)) {
        return Toast('请输入联系电话')
      }
      if (this.company_data.companyMobile.length !== 11) {
        return Toast('请输入正确的联系电话')
      }
      if (!this.notEmpty(this.company_data.cityId)) {
        return Toast('请选择城市')
      }
      if (!this.notEmpty(this.company_data.companyYears)) {
        return Toast('请选择企业年限')
      }
      if (!this.notEmpty(this.company_data.scale)) {
        return Toast('请选择企业规模')
      }
      if (!this.notEmpty(this.company_data.industry)) {
        return Toast('请输入企业类型')
      }

      if (this.updateBel === 1) {
        this.$http({
          method: 'post',
          url: Vue.prototype.AppURL + '/comuser/update/company/data',
          data: this.company_data
        }).then(({ data }) => {
          if (data) {
            Toast('修改成功')
            this.$router.push({name: 'company'})
          }
        })
      } else {
        this.$http({
          method: 'post',
          url: Vue.prototype.AppURL + '/comuser/save/company/data',
          data: this.company_data
        }).then(({ data }) => {
          if (data && data != null) {//data存在并且不为空的话（后台返回的是公司对象）
            localStorage.setItem('status', 1)//status缓存状态
            localStorage.setItem("cache_company_id", data.id);//公司id（把公司信息存在缓存里）
            this.$router.push({name: 'license'})//成功的话跳转到审核页面
          } else {
            return Toast('创建企业信息异常')
          }
        })
      }
    },
    back () {
      this.$router.go(-1) // 返回上一层
    },
    act (i) {
      this.welfare[i].type = !this.welfare[i].type
    },
    tirggerFile: function (event) {//上传头像
      let file = event.target.files[0]
      let url = ''
      var reader = new FileReader()
      reader.readAsDataURL(file)
      let that = this
      reader.onload = function (e) {
        url = this.result.substring(this.result.indexOf(',') + 1)
        that.imgUrl = 'data:image/png;base64,' + url
        that.company_data.logo = url//获取文件流，获取base64
      }
    },
    openImg () {
      this.$refs.input.click()
    },
    prop (i) {
      if (i === 1) {
        this.cityIf = !this.cityIf
      } else if (i === 3) {
        this.stateIf = !this.stateIf
      } else if (i === 5) {
        this.ageIf = !this.ageIf
      }
    },

    addressChange (picker, values) {
      if (this.regionInit) {
        // 给市、县赋值
        picker.setSlotValues(1, this.getCityArr(values[0]['name']))
        picker.setSlotValues(2, this.getCountyArr(values[0]['name'], values[1]['name']))
        // 取值并赋值
        if (values[2] && values[2]['name']) {
          cityValue = values[2]['name']
          cityCode = values[2]['code']
        }
      } else {
        this.regionInit = true
        cityValue = values[2]['name']
        cityCode = values[2]['code']
      }
    },
    // 遍历json，返回省级对象数组
    getProvinceArr () {
      let provinceArr = []
      if (threeLevelAddress) {
        threeLevelAddress.forEach(function (item) {
          let obj = {}
          obj.name = item.name
          obj.code = item.code
          provinceArr.push(obj)
        })
      }
      return provinceArr
    },
    // 遍历json，返回市级对象数组
    getCityArr (province) {
      let cityArr = []
      if (threeLevelAddress) {
        threeLevelAddress.forEach(function (item) {
          if (item.name === province) {
            item.children.forEach(function (args) {
              let obj = {}
              obj.name = args.name
              obj.code = args.code
              cityArr.push(obj)
            })
          }
        })
      }
      return cityArr
    },
    // 遍历json，返回县级对象数组
    getCountyArr (province, city) {
      let countyArr = []
      if (threeLevelAddress) {
        threeLevelAddress.forEach(function (item) {
          if (item.name === province) {
            item.children.forEach(function (args) {
              if (args.name === city) {
                args.children.forEach(function (param) {
                  let obj = {}
                  obj.name = param.name
                  obj.code = param.code
                  countyArr.push(obj)
                })
              }
            })
          }
        })
      }
      return countyArr
    },
    stateChange (picker, values) {
      if (picker.values[0]) {
        stateValue = picker.values[0]['name']
        stateCode = picker.values[0]['id']
      } else {
        if (values[0]) {
          stateValue = values[0]['name']
          stateCode = values[0]['id']
        }
      }

      if (this.updateBel === 1 && picker.slots[0].values) {
        let list = picker.slots[0].values
        list.forEach((item) => {
          if (item.id === (this.company_data.scale - 0)) {
            this.stateValue = item.name
          }
        })
      }
    },
    ageChange (picker, values) {
      if (picker.values[0]) {
        ageValue = picker.values[0]['name']
        ageCode = picker.values[0]['id']
      } else {
        if (values[0]) {
          ageValue = values[0]['name']
          ageCode = values[0]['id']
        }
      }

      if (this.updateBel === 1 && picker.slots[0].values) {
        let list = picker.slots[0].values
        list.forEach((item) => {
          if (item.id === (this.company_data.companyYears - 0)) {
            this.ageValue = item.name
          }
        })
      }
    },
    getCountyData (province, city, xian) {
      let obj = {}
      threeLevelAddress.forEach(function (item) {
        if (item.code === province) {
          item.children.forEach(function (args) {
            if (args.code === city) {
              args.children.forEach(function (param) {
                if (xian === param.code) {
                  obj.name = param.name
                  obj.code = param.code
                }
              })
            }
          })
        }
      })
      return obj
    },
    on (i) {
      if (i === 1) {
        this.cityValue = cityValue
        this.company_data.cityId = cityCode
        this.cityIf = false
      } else if (i === 3) {
        this.stateValue = stateValue
        this.company_data.scale = stateCode
        this.stateIf = false
      } else if (i === 5) {
        this.ageValue = ageValue
        this.company_data.companyYears = ageCode
        this.ageIf = false
      }
    },
    off (i) {
      if (i === 1) {
        cityValue = ''
        this.cityIf = false
      } else if (i === 3) {
        stateValue = ''
        this.stateIf = false
      } else if (i === 5) {
        ageValue = ''
        this.ageIf = false
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
html,
body,
.tac,
.box,
.tab-left,
.tab-left .el-menu {
  height: 100%;
}

.box {
  width: 100%;
  background: #fff;
}
.head-fixed {
  width: 100%;
  height: 43px;
  position: fixed;
  z-index: 999;
}
.head {
  background: #3e63a8;
  color: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}
.back {
  width: 14px;
  height: 14px;
}
.head div img {
  width: 20px;
  height: 20px;
}
.head-search {
  box-sizing: border-box;
  flex: 1;
  text-align: center;
  font-size: 14px;
}
.content {
  position: relative;
  top: 43px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 20px 20px 20px;
}
.inpBox {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  border-bottom: 1px solid #eee;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
}
.inpBox img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.inpBox input {
  border: 0;
  flex: 1;
  outline: none;
  font-size: 14px;
  height: 30px;
  text-align: right;
}
.inpBox div {
  display: flex;
  align-items: center;
}
.inpBoxs {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}
.inpBoxs .inpBox{
    border: 0;
}
.inpBoxs textarea{
    width: 100%;
    height: 150px;
    margin-top: 10px;
    box-sizing: border-box;
    padding: 10px;
}
.welfareClass{
  display: flex;
  flex-wrap: wrap;
  width: 60%;
  box-sizing: border-box;
  justify-content: flex-end;
}
.welfareClass span{
  padding: 3px 5px;
  border: 1px solid #eee;
  margin-right: 10px;
  margin-bottom: 5px;
  font-size: 12px;
}
.active{
  background: #3e63a8;
  color: #fff;
  border-color: #3e63a8 !important;
}
</style>
